﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Web;
using System.Collections.Specialized;

using System.Reflection;

namespace lxwmvc
{
    /// <summary>
    /// 功能:处理Request请求，包括从request捕获数据等基础函数
    /// [09.4.10 lxw]<para />
    /// </summary>
    public class requesthelper 
    {
        /// <summary>
        /// 功能:获取前一个页面的Url地址
        /// [09.4.12 lxw]<para />
        /// </summary>
        /// <returns>返回Url地址字符串</returns>
        public static string formurl()
        {
            NameValueCollection coll = HttpContext.Current.Request.ServerVariables;
            var o = getonevalue("furl");
            //这里还是存在问题。formurl
            if (string.IsNullOrEmpty(o))
            {
                string url = coll["HTTP_REFERER"];
                if (string.IsNullOrEmpty(url)) return "";
                string pre = "";
                string k = "";

                if (url.IndexOf('?') == -1)
                {
                    pre = url;
                }
                else
                {
                    k = url.Substring(url.IndexOf('?') + 1);
                    pre = url.Substring(0, url.IndexOf('?'));
                }

                Dictionary<string, string> di = new Dictionary<string, string>();
                {
                    if (k.Trim() != "")
                    {
                        string[] ks = k.Split(new char[] { '=', '&' });
                        for (int i = 0; i < ks.Length / 2; i++)
                            di[ks[i * 2]] = ks[i * 2 + 1];
                    }
                }
                {
                    k = HttpContext.Current.Request.QueryString.ToString();
                    if (k.Trim() != "")
                    {
                        string[] ks = k.Split(new char[] { '=', '&' });
                        for (int i = 0; i < ks.Length / 2; i++)
                            di[ks[i * 2]] = ks[i * 2 + 1];
                    }
                }

                di.Remove("_controller_");
                di.Remove("_table_");
                di.Remove("_pk_");
                di.Remove("_action_");

                StringBuilder sb = new StringBuilder();
                sb.Append("1=1");
                foreach (var o1 in di)
                {
                    sb.Append("&");
                    sb.Append(o1.Key + "=" + o1.Value);
                }
                //返回数据
                return pre + "?" + sb.ToString();
            }
            else
                return o.tostr();
        }

        /// <summary>
        /// 功能:从Request中获取key对应的value值，主要是把'替换成两个''。使MSSQL语句组合的不产生错误
        /// [09.4.12 lxw]<para />
        /// </summary>
        /// <param name="strKey">request[key]中的key</param>
        /// <returns>返回安全的字符串</returns>
        public static string safekeyvalue(string strKey)
        {
            return getonevalue(strKey).tostr().Replace("'", "''");
        }

        /// <summary>
        /// 获取单条数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string getonevalue(string key)
        {
            string v = "";
            HttpRequest Request = HttpContext.Current.Request;
            if (Request.HttpMethod == "POST")
            {
                //如果查询，直接定位到第一页。
                if (key.ToLower() == "page") return "0";
                v = Request.Form[key];
                if (v == null) v = Request.QueryString[key]??"";
            }
            else
            {
                v = Request.QueryString[key]??"";
            }

            return v;
        }

        /// <summary>
        /// 功能:从url里面的参数中得到对应键的值
        /// [11-03-08 16:02  周二 lxw]<para />
        /// </summary>
        /// <param name="strUrlParams">需要检索的字符串</param>
        /// <param name="strKey">需要找的键</param>
        /// <returns>返回对应键的值</returns>
        public static string fromurlparamsgetvaluebykey(string strUrlParams, string strKey, string split="=")
        {
            int pos = 0;
            int end = 0;

            if ((pos = strUrlParams.ToLower().IndexOf(strKey.ToLower() + split)) != -1)
            {
                end = strUrlParams.ToLower().IndexOf("&", pos);
                if (end == -1) return strUrlParams.Substring(pos + strKey.Length + 1);
     
                if (end - (pos + strKey.Length + 1) == 0) return "";
                
                return strUrlParams.Substring(pos + strKey.Length + 1, end - (pos + strKey.Length + 1));
            }

            return "";
        }

        /// <summary>
        /// 功能:获取客户端IP地址
        /// [09.4.12 lxw]<para />
        /// </summary>
        /// <returns>返回客户端IP地址字符串</returns>
        public static string clientip()
        {
            string strIPAddr = "127.0.0.1";

            try
            {
                HttpRequest Request = HttpContext.Current.Request;
                //if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] == ""
                //    || stringhelper.instr(Request.ServerVariables["HTTP_X_FORWARDED_FOR"], "unknown") > 0
                //    )
                //{
                //    strIPAddr = Request.ServerVariables["REMOTE_ADDR"];
                //}
                //else if (stringhelper.instr(Request.ServerVariables["HTTP_X_FORWARDED_FOR"], ",") > 0)
                //{
                //    strIPAddr = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                //}
                //else if (stringhelper.instr(Request.ServerVariables["HTTP_X_FORWARDED_FOR"], ";") > 0)
                //{
                //    strIPAddr = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                //}
                //else
                //{
                //    strIPAddr = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                //}
                strIPAddr = Request.ServerVariables["REMOTE_ADDR"];

                return strIPAddr.tostr().Split(new char[] { ',', ';' })[0];
            }
            catch
            {
                return strIPAddr;
            }
        }

    }
}
